package ar.com.mooral.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import ar.com.mooral.crohn.CrohnAlarmReceiver;
import ar.com.mooral.crohn.application.CrohnContext;
import ar.com.mooral.crohn.view.CrohnButton;
import ar.com.mooral.crohn.view.CrohnImageView;
import ar.com.mooral.data.Alarms;
import ar.com.mooral.data.GeneralStatus;
import ar.com.mooral.data.Result;
import ar.com.mooral.data.SexualActivityIncidence;
import ar.com.mooral.data.SocialActivityIncidence;
import ar.com.mooral.data.WorkActivityIncidence;
import ar.com.mooral.pojo.AlarmPojo;
import ar.com.mooral.pojo.BasePojo;
import ar.com.mooral.pojo.GeneralStatusPojo;
import ar.com.mooral.pojo.SexualActivityPojo;
import ar.com.mooral.pojo.SocialActivityPojo;
import ar.com.mooral.pojo.util.PojoComparatorDate;

public class Alarma extends CrohnActivity {

	private AlertDialog.Builder alert;
	
	private Context context;
	
	private Alarms alarms;

	private AlarmPojo pojo;
	
	private String uris;
	
	private Vector<CrohnImageView> deleteImageViews;
	
	private ArrayAdapter<String> adapter;

	protected void onStart() {
		super.onStart();
		settings();
	}

	protected void onRestart() {
		super.onRestart();
		settings();
	}
	
	private void settings() {

		String r = "";
		
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(
					"dd/MM/yyyy HH:mm:ss");
			Date date = (Date) formatter.parse(pojo.getDate());

			SimpleDateFormat mysqlFormatter = new SimpleDateFormat(
					"EEEEE, MMMMM d");
			r = mysqlFormatter.format(date);

		} catch (ParseException e) {

		}

		((Button) findViewById(R.id.btnAlarmaFecha)).setText(r);
		
		
		EditText txtCantidadPeriodo = (EditText) findViewById(R.id.txtCantidadPeriodo);
		txtCantidadPeriodo.setText(pojo.getRepeatQuantity());

		Spinner spnPeriodos = (Spinner) findViewById(R.id.spnPeriodos);
		spnPeriodos.setSelection(adapter.getPosition(pojo.getRepeatUnit()));
		
		drawHours(pojo.getHours());
	}
	

	private void drawHours(String hours) {

        
		if (hours.length() == 0)
			return;
		
		String[] data = hours.split(",");
		
		// Clean before addings
		LinearLayout records = (LinearLayout) findViewById(R.id.linearLayoutRegistros);
		records.removeAllViews();

		deleteImageViews = new Vector<CrohnImageView>();

		for (int i = 0; i < data.length; i++) {

			//AlarmPojo record = (AlarmPojo) data[i];

			LinearLayout ll = new LinearLayout(this);
			ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 45));
			ll.setOrientation(LinearLayout.HORIZONTAL);
			ll.setBackgroundResource(R.drawable.medication_bg);
			ll.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
			records.addView(ll);

			CrohnImageView deleteImageView = new CrohnImageView(this);
			deleteImageView.setBackgroundResource(R.drawable.stop);
			deleteImageView.setHour(data[i]);
			//deleteImageView.setVisibility(View.GONE);
			deleteImageView.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {

					//((CrohnImageView) view).setVisibility(View.GONE);
					String hour = ((CrohnImageView) view).getHour();
					pojo.removeHour(hour);
					
					((LinearLayout) view.getParent()).setVisibility(View.GONE);
					
				}
			});
			deleteImageViews.add(deleteImageView);
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(20, 20);

			layoutParams.setMargins(20, 0, 0, 0);			
			ll.addView(deleteImageView, layoutParams);

			CrohnButton recordButton = new CrohnButton(this);
			recordButton.setText(data[i]);
			recordButton.setLayoutParams(new LayoutParams(280, 30));
			recordButton.setBackgroundResource(R.drawable.white);
			recordButton.setTextSize(10);
			ll.addView(recordButton);

		} // for

	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		context = this;
		
		setContentView(R.layout.alarm);

		pojo = (AlarmPojo) CrohnContext.getAlarmPojo();
		uris = pojo.getUris();
		
		
		alarms = new Alarms(this);
		
		
		
		final String[] items = new String[] {"", "Horas", "Dias", "Meses", "Anos"};
		Spinner spinner = (Spinner) findViewById(R.id.spnPeriodos);
		adapter = new ArrayAdapter<String>(this,
		            android.R.layout.simple_spinner_item, items);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
    	spinner.setOnItemSelectedListener(
    	        new AdapterView.OnItemSelectedListener() {
    	        public void onItemSelected(AdapterView<?> parent,
    	            android.view.View v, int position, long id) {
    	        	pojo.setRepeatUnit(items[position]);
    	        }
    	        public void onNothingSelected(AdapterView<?> parent) {
    	        	pojo.setRepeatUnit(items[0]);
    	        }
    	});    	
		
		
		// RETORNO
		Button btnAlarmaCancelar = (Button) findViewById(R.id.btnAlarmaCancelar);
		btnAlarmaCancelar.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				finish();
			}
		});
		

		// REGISTRAR
		Button btnAlarmaGuardar = (Button) findViewById(R.id.btnAlarmaGuardar);
		btnAlarmaGuardar.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				
				
				EditText txtCantidadPeriodo = (EditText) findViewById(R.id.txtCantidadPeriodo);
				pojo.setRepeatQuantity(txtCantidadPeriodo.getText().toString());
				
				
				if (pojo.getHours().equals("")) {
					Result r = new Result("Debe seleccionar por lo menos una hora");
					showMessage(r);
				} else {

					if (pojo.getRepeatQuantity() == null || pojo.getRepeatQuantity().equals("")) {
						pojo.setRepeatQuantity("");
					}
					
					if (pojo.getRepeatUnit() == null || pojo.getRepeatUnit().equals("")) {
						pojo.setRepeatUnit("");
					}
					
					pojo.put("horas", pojo.getHours());
					
					Result r = alarms.save(pojo); 
					if (r.hasError()) { 
						showMessage(r); 
					} else {
						CrohnContext.setAlarmPojo(null);
						
						String id;
						if (pojo.containsKey("id")) {
							id = pojo.get("id");
							try {
								DeleteCalendarEntry();
							} catch(Exception e) {}
						} else {
							id = alarms.getLastInsertId();
							pojo.setId(id);
						}
						
						try {
							String uris = MakeNewCalendarEntry(id, pojo);
							pojo.setUris(uris);
							alarms.save(pojo);
						} catch(Exception e) {}


						finish(); 
					}
				}
			}
		});

		// SELECCION FECHA INICIO
		Button btnAlarmaFecha = (Button) findViewById(R.id.btnAlarmaFecha);
		btnAlarmaFecha.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent = new Intent();
				intent.setComponent(new ComponentName(
						SeleccionFechaAlarma.class.getPackage().getName(),
						SeleccionFechaAlarma.class.getName()));
				startActivity(intent);
			}
		});

		// SELECCION HORA
		Button btnAlarmaAgregarHora = (Button) findViewById(R.id.btnAlarmaAgregarHora);
		btnAlarmaAgregarHora.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent = new Intent();
				intent
						.setComponent(new ComponentName(SeleccionHora.class
								.getPackage().getName(), SeleccionHora.class
								.getName()));
				startActivity(intent);
			}
		});
		
		
		// BORRAR
		Button btnAlarmaBorrar = (Button) findViewById(R.id.btnAlarmaBorrar);
		btnAlarmaBorrar.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
	
				DeleteCalendarEntry();
				
            	alarms.delete(pojo.getId());
            	finish();
			}
		});
		

	}
	
	
/*	
	public void syncSystemCron() {
		
		Vector a = alarms.findAll();
		
		for (int i = 0; i < a.size(); i++) {
			
			Hashtable<String, String> record = (Hashtable<String, String>) a.get(i);
			
			try {
				SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
				Date date = (Date) formatter.parse(record.get("fecha_inicio"));
				
				                
			} catch (Exception e) {
				// TODO: handle exception
			}
			
		}
		
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent alarmIntentRepetitive = new Intent(Alarma.this, CrohnAlarmReceiver.class);
        alarmIntentRepetitive.putExtra("alarm_message", "Mi alarma Repetitiva");
        PendingIntent senderRepetitive = PendingIntent.getBroadcast(context, 192837, alarmIntentRepetitive, PendingIntent.FLAG_UPDATE_CURRENT);

        long firstTime = SystemClock.elapsedRealtime();
        //Si descomentas esta linea ya se activa la alerta.
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 15*1000, senderRepetitive);
		
	}
	
*/
	

    private String MakeNewCalendarEntry(String calId, AlarmPojo pojo) {
    	
    	Vector<Uri> uris = new Vector<Uri>();
    	
    	String rrule = "";
    	int days = 0;
    	if (pojo.getRepeatUnit().equals("Dias")) {
    		rrule = "FREQ=DAYLY";
    		days = 1;
    	} else if (pojo.getRepeatUnit().equals("meses")) {
    		rrule = "FREQ=MONTHLY";
    		days = 30;
    	} else if (pojo.getRepeatUnit().equals("ANOS")) {
    		rrule = "FREQ=YEARLY";
    		days = 365;
    	}
    	
    	// lopp throught each hour
		String[] data = pojo.getHours().split(",");
		for (int i = 0; i < data.length; i++) {

	    	Date date = null;
			try {
				SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm");
				date = (Date) formatter.parse(pojo.getDate() + " " + data[i]);
			} catch (ParseException e) {}
			
			
	        ContentValues event = new ContentValues();

	        event.put("calendar_id", calId.toString() + "");
	        event.put("title", "Tomar medicacion");
	        event.put("description", pojo.getDescription());
	        event.put("eventLocation", "Online");
	        if (days > 0) {
	        	event.put("rrule", rrule);
	        	event.put("duration", "P" + (Integer.parseInt(pojo.getRepeatQuantity()) * days) + "D");
	        }

	        long startTime = date.getTime();
	        long endTime = startTime + 1000 * 60 * 5; // five minutes later

	        event.put("dtstart", startTime);
	        event.put("dtend", endTime);

	        event.put("allDay", 0); // 0 for false, 1 for true
	        event.put("eventStatus", 1);
	        event.put("visibility", 0);
	        event.put("transparency", 0);
	        event.put("hasAlarm", 1); // 0 for false, 1 for true

	        Uri eventsUri = Uri.parse(getCalendarUriBase()+"events");

	        Uri insertedUri = getContentResolver().insert(eventsUri, event);
	        
	        uris.add(insertedUri);
			
		}
		
		String r = "";
		for (int i = 0; i < uris.size(); i++) {
			r += (String)uris.get(i).toString();
			if ((i+1) < uris.size()) {
				r += ";";	
			}
		}
		return r;
    	
    }
	
    
    private void DeleteCalendarEntry() {
    	
		if (uris.length() == 0)
			return;
		
		String[] data = uris.split(",");
		
		for (int i = 0; i < data.length; i++) {
	        //Uri eventsUri = Uri.parse(getCalendarUriBase()+"events");
	        //Uri eventUri = ContentUris.withAppendedId(eventsUri, entryID);
	        int iNumRowsDeleted = getContentResolver().delete(Uri.parse(data[i]), null, null);
		}
    	

    }    
    
    
    /*
     * Determines if it's a pre 2.1 or a 2.2 calendar Uri, and returns the Uri
     */
    private String getCalendarUriBase() {
        String calendarUriBase = null;
        Uri calendars = Uri.parse("content://calendar/calendars");
        Cursor managedCursor = null;
        try {
            managedCursor = managedQuery(calendars, null, null, null, null);
        } catch (Exception e) {
            // eat
        }

        if (managedCursor != null) {
            calendarUriBase = "content://calendar/";
        } else {
            calendars = Uri.parse("content://com.android.calendar/calendars");
            try {
                managedCursor = managedQuery(calendars, null, null, null, null);
            } catch (Exception e) {
                // eat
            }

            if (managedCursor != null) {
                calendarUriBase = "content://com.android.calendar/";
            }

        }

        return calendarUriBase;
    }    
}
